package com.sline.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/file/upload")
public class uploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            for (FileItem fileItem: fileItems) {
//                System.out.println(fileItem.getContentType());
//                System.out.println(fileItem.getFieldName());
//                System.out.println(fileItem.getName());
//                System.out.println(fileItem.isFormField());
                if (fileItem.isFormField()) {
                    System.out.println(fileItem.getString("utf-8"));
                } else {

                    if (!fileItem.getContentType().startsWith("image")) {
                        req.setAttribute("errorMsg", "您上传的不是图片, 请检查后重新上传");
                        req.getRequestDispatcher("/upload/uploadImage.jsp").forward(req, resp);
//                        throw new FileUDException("您上传的不是图片, 请检查后重新上传");
                    }

                    String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileItem.getName());
                    File savePath = new File(req.getServletContext().getRealPath("/upload/images"));
                    if (!savePath.exists()) {
                        savePath.mkdirs();
                    }

                    fileItem.write(new File(savePath.getPath()+ "/", fileName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
